import copy
from rest_framework.views import APIView
from SecureHelperServer.settings import formatResponseData
from utils.conf import getUserByToken, Response
from rest_framework_simplejwt.settings import api_settings


class GetUserInfoView(APIView):
    # 局部(本视图有效)身份认证
    authentication_classes = []
    # 局部(本视图有效)权限认证
    permission_classes = []

    def post(self, request, *args, **kwargs):
        """
        个人中心-获取用户信息
        """
        data = copy.deepcopy(formatResponseData)
        try:
            token = None
            headerToken = request.META.get(api_settings.AUTH_HEADER_NAME, "")
            tokenTopAndEnd = headerToken.split(" ")

            if len(tokenTopAndEnd) == 2:
                token = tokenTopAndEnd[1]

            if not token:
                return Response(data=data, loggerMsg="个人中心-获取用户信息：用户未登录", isError=True)

            user = getUserByToken(token)
            userInfo = {
                'username': user.username,
                'email': user.email,
                'gender': user.gender,
                'birthday': user.birthday,
                'bindCode': user.bindCode,
                'headSculptureUrl': user.headSculpture.url,
                'needAudio': user.needAudio,
                "isLogin": True
            }

            data["data"]["userInfo"] = userInfo
            return Response(data=data, loggerMsg=f"个人中心-获取用户信息: 成功，uid={user.uid}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
